<template>
  <div>
    <!-- 页面标题和说明 -->
    <!-- 操作栏 -->
    <el-card shadow="never" class="mb-5 border-box">
      <el-row justify="space-between" align="middle" :gutter="10" class="mb-6">
        <el-col :lg="12" :md="12" :sm="14" :xs="16">
          <div class="flex gap-2">
            <el-input
              v-model="searchVal"
              :prefix-icon="Search"
              clearable
              placeholder="输入景点名称查询"
              class="w-250px!"
              @input="searchAttractions"
            />
            <el-button type="primary" @click="toAddAttraction">
              <el-icon>
                <Plus />
              </el-icon>
              添加景点
            </el-button>
          </div>
        </el-col>
        <el-col :lg="12" :md="12" :sm="0" :xs="0">
          <div class="custom-segmented flex justify-end">
            <el-radio-group v-model="statusFilter" size="default" @change="filterByStatus">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="open">开放中</el-radio-button>
              <el-radio-button label="maintenance">维护中</el-radio-button>
              <el-radio-button label="closed">已关闭</el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <div class="page-content attraction-list">
      <!-- 景点列表 -->
      <div v-if="!showEmpty"  class="h-[calc(100vh-313px)] overflow-y-auto">
        <el-row :gutter="20" v-if="!showEmpty" class="overflow-y-auto">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="item in attractionList"
            :key="item.id"
            class="mb-5"
          >
            <el-card
              :body-style="{ padding: '0px', height: '100%' }"
              shadow="hover"
              class="attraction-card"
            >
              <!-- 骨架屏 -->
              <el-skeleton animated :loading="isLoading" class="w-full h-full">
                <template #template>
                  <div class="aspect-ratio-16/9"></div>
                  <div class="p-3.5">
                    <el-skeleton-item variant="h3" class="w-4/5" />
                    <div class="flex items-center mt-2">
                      <el-skeleton-item variant="text" class="mr-4" />
                      <el-skeleton-item variant="text" class="w-3/10" />
                    </div>
                    <el-skeleton-item variant="text" class="w-full mt-4" />
                    <el-skeleton-item variant="text" class="w-full mt-2" />
                  </div>
                </template>

                <template #default>
                  <div class="w-full h-full flex flex-col">
                    <!-- h-125px修改图片大小 -->
                    <el-image
                      v-if="JSON.parse(item.imageUrl || '[]').length"
                      class="attraction-image w-full h-180px object-cover"
                      :src="JSON.parse(item.imageUrl || '[]')[0].path"
                      fit="cover"
                    >
                      <template #error>
                        <div
                          class="image-slot flex justify-center items-center w-full h-full bg-fill-light text-text-secondary text-30px"
                        >
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div
                      v-else
                      class="image-slot flex justify-center items-center h-180px w-full bg-fill-light text-text-secondary text-30px"
                    >
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>

                    <div class="flex-1">
                      <div class="p-3 h-full box-border flex flex-col">
                        <div class="flex justify-between items-start">
                          <h3 class="text-lg font-medium line-clamp-1">{{ item.spotName }}</h3>
                          <el-tag :type="getStatusType(item.operationStatus || 1) as any">
                            {{ statusTextMap[item.operationStatus || 1] }}
                          </el-tag>
                        </div>
                        <div class="text-sm text-gray-500 mt-1 flex items-center">
                          <el-icon>
                            <Location />
                          </el-icon>
                          <span class="ml-1 line-clamp-1">{{ item.location }}</span>
                        </div>
                        <p
                          class="text-sm text-gray-600 mt-2 line-clamp-2 whitespace-pre-line break-all"
                        >
                          {{ item.introduce }}
                        </p>
                        <div class="flex justify-end items-center mt-auto pt-1">
                          <!-- <el-rate
                                                        :model-value="getRating(item.rating)"
                                                        disabled
                                                        text-color="#ff9900"
                                                    /> -->
                          <div class="action-buttons">
                            <el-button
                              type="primary"
                              text
                              size="small"
                              @click.stop="viewDetail(item)"
                            >
                              <el-icon><View /></el-icon>查看
                            </el-button>
                            <el-button
                              type="primary"
                              text
                              size="small"
                              @click.stop="editAttraction(item)"
                            >
                              <el-icon><Edit /></el-icon>编辑
                            </el-button>
                            <el-button
                              type="danger"
                              text
                              size="small"
                              @click.stop="confirmDelete(item)"
                            >
                              <el-icon><Delete /></el-icon>删除
                            </el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </el-skeleton>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-313px)]" v-if="showEmpty">
        <el-empty description="暂无景点数据" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { router } from '@/router'
  import { Search, Picture, Location, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { jingdivo } from '@/api/4a/types'
  import {
    scenicScenicSpotDeleteScenicSpotUsingGet,
    scenicScenicSpotPageScenicSpotUsingPost
  } from '@/api/4a'

  // 请求参数
  const formData = ref({
    current: 1,
    size: 8,
    like: '',
    operationStatus: undefined as number | undefined
  })

  // 状态过滤器
  const statusFilter = ref('all')

  // 搜索值
  const searchVal = ref('')

  // 景点列表数据
  const attractionList = ref<jingdivo[]>([])

  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(8)
  const total = ref(0)
  const isLoading = ref(true)

  // 状态映射
  const statusTextMap: Record<number, string> = {
    1: '开放中',
    2: '部分维修',
    3: '维护中',
    4: '已关闭'
  }

  const statusValueMap: Record<string, number | undefined> = {
    all: undefined,
    open: 1,
    maintenance: 3,
    closed: 4
  }

  // 评分值
  // const getRating = (rating: string | undefined) => {
  //     return rating ? Number(rating) : 0
  // }

  // 空状态判断
  const showEmpty = computed(() => {
    return attractionList.value.length === 0 && !isLoading.value
  })

  // 获取景点列表
  const getAttractionList = async () => {
    isLoading.value = true

    try {
      // 更新formData
      formData.value.current = currentPage.value
      formData.value.size = pageSize.value
      formData.value.like = searchVal.value
      formData.value.operationStatus = statusValueMap[statusFilter.value]

      const res = await scenicScenicSpotPageScenicSpotUsingPost({
        body: formData.value
      })

      if (res.code === 0) {
        attractionList.value = res.data?.list || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error('获取景点列表失败')
      }
    } catch (error) {
      console.error('获取景点列表失败', error)
      ElMessage.error('获取景点列表失败')
    } finally {
      isLoading.value = false
    }
  }

  // 状态标签类型
  const getStatusType = (status: number) => {
    switch (status) {
      case 1:
        return 'success'
      case 2:
        return 'warning'
      case 3:
        return 'info'
      case 4:
        return 'danger'
      default:
        return ''
    }
  }

  // 生命周期钩子
  onActivated(() => {
    getAttractionList()
  })

  // 查看详情
  const viewDetail = (item: jingdivo) => {
    router.push({
      path: `/attraction/detail`,
      query: {
        id: item.id
      }
    })
  }

  // 编辑景点
  const editAttraction = (item: jingdivo) => {
    router.push({
      path: `/attraction/edit`,
      query: {
        id: item.id
      }
    })
  }

  // 添加新景点
  const toAddAttraction = () => {
    router.push({
      path: `/attraction/edit`
    })
  }

  // 删除确认
  const confirmDelete = (item: jingdivo) => {
    ElMessageBox.confirm(`确定要删除景点 "${item.spotName}" 吗？此操作不可恢复！`, '删除提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        deleteAttraction(item.id)
      })
      .catch(() => {
        // 取消删除
      })
  }

  // 删除景点
  const deleteAttraction = async (id?: string | number) => {
    if (!id) {
      ElMessage.error('景点ID不能为空')
      return
    }

    try {
      const res = await scenicScenicSpotDeleteScenicSpotUsingGet({
        params: { scenicSpotId: id }
      })

      if (res.code === 0) {
        ElMessage.success('删除成功')
        getAttractionList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除景点失败', error)
      ElMessage.error('删除景点失败')
    }
  }

  // 搜索景点
  const searchAttractions = () => {
    currentPage.value = 1
    getAttractionList()
  }

  // 状态过滤
  const filterByStatus = () => {
    currentPage.value = 1
    getAttractionList()
  }

  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getAttractionList()
  }

  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getAttractionList()
  }
</script>

<style lang="scss" scoped>
  .attraction-list {
    .attraction-card {
      height: 100%;
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-5px);

        @apply shadow-lg shadow-black/5;
      }
    }

    .action-buttons {
      display: flex;
      gap: 4px;

      .el-button {
        padding: 6px 8px;

        .el-icon {
          margin-right: 2px;
        }
      }
    }
  }

  .border-box {
    border-radius: 8px !important;

    :deep(.el-card__body) {
      padding-bottom: 0 !important;
    }
  }
</style>
